package jch.learn.java.advanced.chapter2_InputAndOutput;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

public class TestFilesCMD {

    public static void main(String[] args) throws IOException {
        create();
        System.out.println("test/a目录：");
        show(Paths.get("test/a"));

        System.out.println("test/b目录：");
        show(Paths.get("test/b"));

        // 将文件复制到另一个位置
        System.out.println("将文件c.txt从test/a目录复制到test/b");

        Files.copy(Paths.get("test/a/c.txt"), Paths.get("test/b/c.txt"));

        System.out.println("检查test/b目录：");
        show(Paths.get("test/b"));

        System.out.println("移动文件(即复制并删除源文件)：");

        Files.move(Paths.get("test/b/c.txt"), Paths.get("test/a/c2.txt"));

        System.out.println("检查test/a目录：");
        show(Paths.get("test/a"));

        System.out.println("删除test/a/c2.txt文件：");

        Files.delete(Paths.get("test/a/c2.txt"));

        System.out.println("检查test/a目录：");
        show(Paths.get("test/a"));

        System.out.println("删除test/g:");
        Files.deleteIfExists(Paths.get("test/a/c2.txt"));

        Files.deleteIfExists(Paths.get("test/g"));
        System.out.println("展示test/a：");
        show(Paths.get("test/a"));
    }

    private static void show(Path path){
        for (File f : Objects.requireNonNull(path.toFile().listFiles())) {
            System.out.println(f.getName());
        }
    }

    private static void create() throws IOException {
        if (Files.notExists(Paths.get("test/a"), LinkOption.NOFOLLOW_LINKS)) {
            Path a = Files.createDirectories(Paths.get("test/a"));
            System.out.println(a);
            Path c = Files.createFile(Paths.get("test/a/c.txt"));
            Files.write(c, "c".getBytes(StandardCharsets.UTF_8));
            Path d = Files.createFile(Paths.get("test/a/d.txt"));
            Files.write(d, "d".getBytes(StandardCharsets.UTF_8));
        }
        if (Files.notExists(Paths.get("test/b"), LinkOption.NOFOLLOW_LINKS)) {
            Path b = Files.createDirectory(Paths.get("test/b"));
            System.out.println(b);
            Path c1 = Files.createFile(Paths.get("test/b/c1.txt"));
            Files.write(c1, "c1".getBytes(StandardCharsets.UTF_8));
            Path d1 = Files.createFile(Paths.get("test/b/d1.txt"));
            Files.write(d1, "d1".getBytes(StandardCharsets.UTF_8));
        }
        if (Files.notExists(Paths.get("test/g"),LinkOption.NOFOLLOW_LINKS)){
            Files.createDirectory(Paths.get("test/g"));
        }
    }
}
